from OWRpy import *
import os.path, redREnviron
import redRi18n
_ = redRi18n.get_(package = 'cluster')

# signal classes
from libraries.base.signalClasses.RVariable import RVariable as redRRVariable
from libraries.base.signalClasses.RDataFrame import RDataFrame as redRRDataFrame
from libraries.base.signalClasses.RList import RList as redRRList

# Qt widgets
from libraries.base.qtWidgets.comboBox import comboBox
from libraries.base.qtWidgets.lineEdit import lineEdit
from libraries.base.qtWidgets.groupBox import groupBox
from libraries.base.qtWidgets.tabWidget import tabWidget
from libraries.base.qtWidgets.button import button
from libraries.base.qtWidgets.radioButtons import radioButtons as redRradioButtons
from libraries.base.qtWidgets.commitButton import commitButton as redRCommitButton



class clusPlot(OWRpy): 
    globalSettingsList = ['commit']
    settingsList = []
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
       
        # Python variables
        self.data = {}
        self.RFunctionParam_x = ''
        
        # Unique R variables
        #self.setRvariableNames(["defaultILRbase"])
        
        # Inputs
        self.inputs.addInput('id0', 'Data frame', redRRDataFrame, self.processx)
        
        # GUI
        area = redRGUI.base.widgetBox(self.controlArea,orientation='vertical')
        box = redRGUI.base.widgetBox(area)
        area.layout().setAlignment(box,Qt.AlignLeft)
        
        self.RFunctionParam_clus = redRListBox(area, label = _('Select cluster factor column'))
        self.RFunctionParam_clus.setSelectionMode(QAbstractItemView.SingleSelection)
        
        genOptions = tabWidget(self.controlArea)
        self.optionsTab1 = genOptions.createTabPage(name = "Options 1",orientation='vertical')
        self.optionsTab2 = genOptions.createTabPage(name = "Options 2",orientation='vertical')

        self.RFunctionParam_diss = redRradioButtons(self.optionsTab1,  label = "Object", 
        buttons = [('TRUE','Dissimilarity matrix'), ('FALSE','Matrix of observations')],
        setChecked='FALSE',orientation='horizontal', callback = self.onTestChange)
        self.RFunctionParam_cor = redRradioButtons(self.optionsTab1,  label = "Scale to unit variance", 
        buttons = [('TRUE','Yes'), ('FALSE','No')],
        setChecked='TRUE',orientation='horizontal')
        self.RFunctionParam_stand = redRradioButtons(self.optionsTab1,  label = "Standardize representation", 
        buttons = [('TRUE','Yes'), ('FALSE','No')],
        setChecked='FALSE',orientation='horizontal')
        self.RFunctionParam_lines = redRradioButtons(self.optionsTab1,  label = "Distance lines", 
        buttons = [('0','None'), ('1','Between centers'), ('2','Between boundaries')],
        setChecked='2',orientation='horizontal')
        self.RFunctionParam_shade = redRradioButtons(self.optionsTab1,  label = "Shade", 
        buttons = [('TRUE','Yes'), ('FALSE','No')],
        setChecked='FALSE',orientation='horizontal')
        self.RFunctionParam_color = redRradioButtons(self.optionsTab1,  label = "Color", 
        buttons = [('TRUE','Yes'), ('FALSE','No')],
        setChecked='FALSE',orientation='horizontal')
        self.RFunctionParam_span = redRradioButtons(self.optionsTab1,  label = "Ellipses", 
        buttons = [('TRUE','Smallest area containing all its points'), ('FALSE','Based on the mean and covariance matrix')],
        setChecked='TRUE',orientation='vertical')
        
        self.RFunctionParam_labels = redRradioButtons(self.optionsTab2,  label = "Labels", 
        buttons = [('0','None'), ('1','Identify'), ('2','Points and ellipses'), ('3','Only points'), ('4','Only ellipses'), ('5','Only ellipses, Identify')],setChecked='0',orientation='vertical')
        self.RFunctionParam_plotchar = redRradioButtons(self.optionsTab2,  label = "Plotting symbols different", 
        buttons = [('TRUE','Yes'), ('FALSE','No')],
        setChecked='TRUE',orientation='horizontal')
        self.RFunctionParam_colp = lineEdit(self.optionsTab2, label = "Color code(s) for points:", text = '')
        self.RFunctionParam_coltxt = lineEdit(self.optionsTab2, label = "Color code(s) for labels:", text = '')
        self.RFunctionParam_colclus = lineEdit(self.optionsTab2, label = "Color code for ellipses:", text = '')
        self.RFunctionParam_xlim = lineEdit(self.optionsTab2, label = "x - range (comma seperated)", text = '')
        self.RFunctionParam_ylim = lineEdit(self.optionsTab2, label = "y - range (comma seperated)", text = '')
        self.RFunctionParam_main = lineEdit(self.optionsTab2, label = "Main title: ", text = '')
        self.RFunctionParam_sub = lineEdit(self.optionsTab2, label = "Subtitle: ", text = '')
        
        box.setMinimumWidth(200)
        buttonBox = redRGUI.base.widgetBox(box,orientation='horizontal')
        self.commit = redRGUI.base.commitButton(buttonBox, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True,processOnChange=True)

    def onTestChange(self):
        if self.RFunctionParam_diss.getChecked() =='Dissimilarity matrix' :
            self.RFunctionParam_cor.setDisabled(True)
        elif self.RFunctionParam_diss.getChecked() =='Matrix of observations' :
            self.RFunctionParam_cor.setEnabled(True)


    def processx(self, data):
        if not self.require_librarys(["cluster"]):
            self.status.setText('R Libraries Not Loaded.')
            return        
        if data:
            self.RFunctionParam_x=data.getData()
            self.RFunctionParam_clus.update(self.R('names('+self.RFunctionParam_x+')', wantType = 'list'))
            #self.commitFunction()
        else:
            self.RFunctionParam_x = ''

    def commitFunction(self):
        if str(self.RFunctionParam_x) == '': 
            self.status.setText('No data')
            return      

        self.R('rSelected<-'+unicode(self.RFunctionParam_x)+'[,'+unicode(self.RFunctionParam_clus.row(self.RFunctionParam_clus.currentItem())+1)+']')
        
        injection = []
        injection.append('diss='+str(self.RFunctionParam_diss.getCheckedId())+'')
        injection.append('cor='+str(self.RFunctionParam_cor.getCheckedId())+'')
        injection.append('stand='+str(self.RFunctionParam_stand.getCheckedId())+'')
        injection.append('lines='+str(self.RFunctionParam_lines.getCheckedId())+'')
        injection.append('shade='+str(self.RFunctionParam_shade.getCheckedId())+'')
        injection.append('color='+str(self.RFunctionParam_color.getCheckedId())+'')
        injection.append('span='+str(self.RFunctionParam_span.getCheckedId())+'')
        injection.append('labels='+str(self.RFunctionParam_labels.getCheckedId())+'')
        injection.append('plotchar='+str(self.RFunctionParam_plotchar.getCheckedId())+'')
        if str(self.RFunctionParam_colp.text()) != '':
            injection.append('col.p="'+str(self.RFunctionParam_colp.text())+'"')
        if str(self.RFunctionParam_coltxt.text()) != '':
            injection.append('col.txt="'+str(self.RFunctionParam_coltxt.text())+'"')
        if str(self.RFunctionParam_colclus.text()) != '':
            injection.append('col.clus="'+str(self.RFunctionParam_colclus.text())+'"')
        if str(self.RFunctionParam_xlim.text()) != '':
            injection.append('xlim=c('+str(self.RFunctionParam_xlim.text())+')')
        if str(self.RFunctionParam_ylim.text()) != '':
            injection.append('ylim=c('+str(self.RFunctionParam_ylim.text())+')')
        if str(self.RFunctionParam_main.text()) != '':
            injection.append('main="'+str(self.RFunctionParam_main.text())+'"')
        if str(self.RFunctionParam_sub.text()) != '':
            injection.append('sub="'+str(self.RFunctionParam_sub.text())+'"')
        
        inj = ','.join(injection)


        self.R('clusplot('+str(self.RFunctionParam_x)+',rSelected,'+inj+')')